<?php
declare (strict_types=1);

namespace app\command;

use app\admin\model\MessageTemplate;
use app\home\model\AmountLog;
use app\home\model\Config;
use app\home\model\IntegralLog;
use app\home\model\User;
use app\home\model\UserCommission;
use app\home\model\UserCoupon;
use app\merchant\model\Goods;
use app\merchant\model\UserConsumption;
use app\services\wechat\Offiaccount;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Exception;

/**
 * Class Coupon
 * 修改 失效优惠券
 */
class GoodsOrder extends Command{
    protected function configure()
    {
        $this->setName('goodsorder')->setDescription('GoodsOrder');
    }

    /**
     * execute()方法 就是 运行该命令行类的时候要执行的具体业务逻辑代码
     */
    protected function execute(Input $input, Output $output)
    {

        for ($i=0;$i<3;$i++){

            $UserConsumptionModel = new UserConsumption();
            $list = $UserConsumptionModel
            ->where(['pay_status' => 1])
            ->select()->toArray();
            foreach ($list as  $value) {
                if ($value['pay_type'] == 7){
                    $offiaccount  = new Offiaccount();
                    $rechargeInfo = $offiaccount->orderquery($value);
                    if ($rechargeInfo['return_code'] == 'SUCCESS') {
                        if ($rechargeInfo['result_code'] == 'SUCCESS') {
                            if ($rechargeInfo['trade_state'] == 'SUCCESS') {
                          $this->handleData($value);
                        }elseif ($rechargeInfo['trade_state'] == 'CLOSED' || $rechargeInfo['trade_state'] == 'PAYERROR' || $rechargeInfo['trade_state'] == 'NOTPAY' || $rechargeInfo['trade_state'] == 'REFUND') {
                                if (time() - $value['pay_time'] > 120) {
                                    $UserConsumptionModel->where(['id' => $value['id']])->update(['pay_status' => 3, 'update_time' => time()]);
                                }
                            }
                        }
                    }
                }else if ($value['pay_type'] == 8){
                    $AliOffiaccount  = new \app\services\alipay\Offiaccount();
                    $aliOrderInfo = $AliOffiaccount->orderquery($value);
                    if ($aliOrderInfo['alipay_trade_query_response']['code'] == 10000){
                        if ($aliOrderInfo['alipay_trade_query_response']['trade_status'] == 'TRADE_SUCCESS'){
                            $this->handleData($value);
                        }
                    }
                }
            }
            $output->writeln('成功');
            sleep(20);

        };
    }

    public  function handleData ($data){
        try{
            $userModel  = new User();
            $userInfo = $userModel->where(['id' => $data['uid']])->find();
            $UserConsumptionModel = new UserConsumption();
            $UserConsumptionModel->where(['id' => $data['id']])
                ->update(['pay_status' => 4]);
            $UserConsumptionModel->startTrans();
            $UserConsumptionModel->where(['id' => $data['id']])
                ->update([
                    'pay_status' => 2,
                    'status' => 2,
                    'update_time' => time(),
                    'pay_time' => time(),
                ]);
            switch ($data['pay_type']) {
                case 7:
                    $operate_type =  26;
                    $pay_type =  1;
                    $pay_method = 1;
                    $messagePayType = '微信';
                    break;
                case 8:
                    $operate_type =  27;
                    $pay_type =  1;
                    $pay_method = 2;
                    $messagePayType = '支付宝';
                    break;
            }
            $AmountLogData = [  // 金额扣除记录
                'uid' => $data['uid'],
                'amount' => $data['amount'],
                'create_time' => time(),
                'operate_type' => $operate_type,
                'pay_type' => $pay_type,
                'pay_method' => $pay_method,
                'order_id' => $data['id'],
                'order_sn' => $data['sn_order'],
                'ratio' => 1,
                'type' => 2,
                'staff_id' => $data['staff_id'],
                'store_id' => $data['store_id']
            ];
            $amountLogModel = new AmountLog();
            $amountLogModel->insert($AmountLogData); // 收银记录
            if ($data['store_id']> 0){
                $storeModel = new \app\merchant\model\Store();
                $storeModel->where(['id' => $data['store_id']])->inc('goods_amount',(float)$data['amount'])->update();
            }

            if ($data['get_integral']>0) {
                $userAddIntegralData = [  // 添加用户积分
                    'mode_type' => 8,
                    'type' => 1,
                    'deduction_ratio' => $data['get_integral_ratio'],
                    'num' => $data['get_integral'],
                    'uid' => $userInfo['id'],
                    'create_time' => time(),
                    'order_id' => $data['id']
                ];  // 用户积分添加记录
                $IntegralLogModel = new IntegralLog();
                $IntegralLogModel->insert($userAddIntegralData);
            }
            $userModel->where(['id' => $data['uid']])
                ->inc('integral', (float)$data['get_integral'])
                ->inc('surplus_integral', (float)$data['get_integral'])
                ->inc('consumption_amount', (float)$data['amount'])
                ->update();
            $userModel->updateUserLevel($data['uid'], bcadd($userInfo['consumption_amount'], $data['amount'], 2));
            $distribution_level = Config::getConfigValue('distribution_level');
            $firstCommissionData = [];
            $secondCommissionData = [];
            // 佣金
            if ($distribution_level > 0) {
                if ($userInfo['pid'] > 0) {
                    $first_commission = Config::getConfigValue('first_commission');
                    if ($first_commission) {
                        $pUserInfo = $userModel->where(['id' => $userInfo['pid']])->find();
                        $userCommissionModel = new UserCommission();
                        $firstCommissionData = [
                            'trigger_uid' => $userInfo['id'],
                            'receive_uid' => $userInfo['pid'],
                            'level' => 1,
                            'amount' => bcdiv(bcmul((string)$data['amount'], (string)$first_commission, 2), '100', 2),
                            'ratio' => $first_commission,
                            'order_id' => $data['id'],
                            'create_time' => time(),
                            'type' => 1,
                        ];
                        $userCommissionModel->insert($firstCommissionData);
                        $userModel->where(['id' => $userInfo['pid']])
                            ->inc('total_commission', (float)bcdiv(bcmul((string)$first_commission, (string)$data['amount'], 2), '100', 2))
                            ->inc('surplus_commission', (float)bcdiv(bcmul((string)$first_commission, (string)$data['amount'], 2), '100', 2))
                            ->update();
                    }
                    if ($distribution_level >= 2) {
                        $second_commission = Config::getConfigValue('second_commission');
                        if ($second_commission > 0 && $pUserInfo['pid'] > 0) {
                            $ppUserInfo = $userModel->where(['id' => $pUserInfo['pid']])->find();
                            $userCommissionModel = new UserCommission();
                            $secondCommissionData = [
                                'trigger_uid' => $userInfo['id'],
                                'receive_uid' => $pUserInfo['pid'],
                                'level' => 2,
                                'amount' => bcdiv(bcmul((string)$data['amount'], (string)$second_commission, 2), '100', 2),
                                'ratio' => $second_commission,
                                'order_id' => $data['id'],
                                'create_time' => time(),
                                'type' => 1,
                            ];
                            $userCommissionModel->insert($secondCommissionData);
                            $userModel->where(['id' => $pUserInfo['pid']])
                                ->inc('total_commission',(float) bcdiv(bcmul((string)$second_commission, (string)$data['amount'], 2), '100', 2))
                                ->inc('surplus_commission', (float)bcdiv(bcmul((string)$second_commission, (string)$data['amount'], 2), '100', 2))
                                ->update();
                        }
                    }
                }
            }
            $UserConsumptionModel->commit();
        }catch (Exception $exception){
            $UserConsumptionModel->rollback();
            $UserConsumptionModel->where(['id' => $data['id']])->update(['pay_status' => 1]);
            return ['code'=> 0 ,$exception->getMessage()];
        }
        $messageModel = new MessageTemplate();
        if ($data['get_integral'] > 0) {
            $messageModel->sendMessage($userInfo['openid'], [
                'thing2' => ['value' => '积分'],
                'amount8' => ['value' => $data['get_integral'] . '分'],
                'amount6' => ['value' => bcadd((string)$userInfo['surplus_integral'], $data['get_integral'], 2)],
                'time4' => ['value' => date('Y-m-d H:i')]], 'integral_add'); //
        }
        if ($firstCommissionData) { // 一级分佣
            $messageModel->sendMessage($pUserInfo['openid'], [
                'thing2' => ['value' => '直推佣金'],
                'amount8' => ['value' => $firstCommissionData['amount']],
                'amount6' => ['value' => bcadd((string)$pUserInfo['surplus_commission'], (string)$firstCommissionData['amount'], 2)],
                'time4' => ['value' => date('Y-m-d H:i')]], 'commission_add'); //
        }
        if ($secondCommissionData) { // 一级分佣
            $messageModel->sendMessage($ppUserInfo['openid'], [
                'thing2' => ['value' => '间推佣金'],
                'amount8' => ['value' => $secondCommissionData['amount']],
                'amount6' => ['value' => bcadd((string)$ppUserInfo['surplus_commission'], (string)$secondCommissionData['amount'], 2)],
                'time4' => ['value' => date('Y-m-d H:i')],
            ], 'commission_add'); //
        }
    }
}